package com.hackdf.ecographic;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;

import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class Utilities {

	Connection conn;
	Statement st;
	ResultSet rs = null;
	
	
	public void CloseConnection(){
		if(conn!=null){
			try {
				conn.close();
				st.close();
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
	public Utilities(Context ctx){
		if(conn == null){
			try {
				Class.forName(ctx.getString(R.string.mensajeinicio));
				conn = DriverManager.getConnection(ctx.getString(R.string.textotitulo), ctx.getString(R.string.textotoolbar), ctx.getString(R.string.mensajealerta));
				DriverManager.setLoginTimeout(10);
				st = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
						ResultSet.CONCUR_READ_ONLY, 
						ResultSet.HOLD_CURSORS_OVER_COMMIT);

			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	public ResultSet RemoteConnection(String query, Context ctx, String tag){

		try {
			
			Log.i(""+tag, ""+query);
			rs = st.executeQuery(query);
			if(rs.first()){
				ResultSetMetaData rsmd = rs.getMetaData();
				StringBuilder sb = new StringBuilder();
				int columnCount = rsmd.getColumnCount();
				for (int i = 1; i < columnCount + 1; i++ ) {
					sb.append(" "+rsmd.getColumnName(i)+" ");
				}
				Log.i(""+tag, "column names "+sb.toString());
				return rs;
			}else{
				Log.i(""+tag, query+" --> sin resultados");
				return null;
			}
		} catch (Exception e) {
			conn = null;
			e.printStackTrace();
			return null;
		}
	}
	
	
	public boolean RemoteInsert(String query, Context ctx, String TAG) throws SQLException {
		

        try {
        	Class.forName(ctx.getString(R.string.mensajeinicio));
			conn = DriverManager.getConnection(ctx.getString(R.string.textotitulo), ctx.getString(R.string.textotoolbar), ctx.getString(R.string.mensajealerta));
			DriverManager.setLoginTimeout(10);
//			st = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
//					ResultSet.CONCUR_READ_ONLY, 
//					ResultSet.HOLD_CURSORS_OVER_COMMIT);
			Log.i(""+TAG, ""+query);
			st.execute(query);
            return true;
        } catch (Exception e) {
            System.out.println( "Error al hacer el insert: " + e.toString() );
            e.printStackTrace();
            return false;
        }
    }
	
	
	public static void badge(String packageName, String className, int number, Context ctx){

        Intent intent = new Intent("android.intent.action.BADGE_COUNT_UPDATE");
        intent.putExtra("badge_count", number);
        intent.putExtra("badge_count_package_name", packageName);
        intent.putExtra("badge_count_class_name", className );
        ctx.getApplicationContext().sendBroadcast(intent);

}


}
